//
//  editIntroduceController.m
//  SoundPill
//
//  Created by 宋旭东 on 15/7/2.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "editIntroduceController.h"
#import "AFNetworking.h"
#import "JCAlertView.h"
@interface editIntroduceController ()<UITextViewDelegate>
{
    UITextView *textfield;
    UIBarButtonItem *sureBtn;
    UILabel *textlength;
}
@end

@implementation editIntroduceController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"修改签名";
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    [back setFrame:CGRectMake(0, 0, 30, 30)];
    [back setImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:back];
    self.navigationItem.leftBarButtonItem = backItem;
    
    
    UIButton *sure = [UIButton buttonWithType:UIButtonTypeCustom];
    [sure setFrame:CGRectMake(0, 0, 30, 30)];
    [sure setImage:[UIImage imageNamed:@"done"] forState:UIControlStateNormal];
    [sure addTarget:self action:@selector(sureIntroduceClick) forControlEvents:UIControlEventTouchUpInside];
    sureBtn = [[UIBarButtonItem alloc] initWithCustomView:sure];
//    sureBtn = [[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(sureIntroduceClick)];
//    sureBtn.tintColor = [UIColor blackColor];
    self.navigationItem.rightBarButtonItem = sureBtn;
    
    //self.navigationItem.rightBarButtonItem.title = @"确定";
    
    sureBtn.enabled = NO;

    self.view.backgroundColor = [UIColor whiteColor];
//    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];

    
    textfield = [[UITextView alloc]initWithFrame:CGRectMake(self.view.frame.size.width*0.04, 10, self.view.frame.size.width*0.92, self.view.frame.size.height * 0.2)];
    textfield.backgroundColor = [UIColor colorWithRed:0.5 green:0.5 blue:0.4 alpha:0.1];
    textfield.textColor = [UIColor blackColor];
    textfield.textAlignment = NSTextAlignmentCenter;

    textfield.delegate = self;
    textfield.enablesReturnKeyAutomatically = YES;
    //读取字典类型NSDictionary类型的数据
//    NSString *str =(NSString *)[userDefaultes valueForKey:@" introduce"];
    textfield.text = [[[NSUserDefaults standardUserDefaults] valueForKey:@"myDictionary"] valueForKey:@"introduce"];;
    textfield.layer.cornerRadius = 6;
    textfield.layer.masksToBounds = YES;
    UIColor *customColor  = [UIColor colorWithWhite:0.775 alpha:1.000];
    textfield.layer.borderColor = customColor.CGColor;
    textfield.layer.borderWidth = 1.0;
    textfield.font = [UIFont systemFontOfSize:16];
    textfield.returnKeyType = UIReturnKeyDone;
    textfield.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:textfield];
    
    textlength = [[UILabel alloc] initWithFrame:CGRectMake(textfield.frame.size.width - 20, textfield.frame.size.height - 15, 30, 20)];
    textlength.textAlignment = NSTextAlignmentCenter;
    textlength.text = [NSString stringWithFormat:@"%lu", 40 - textfield.text.length];
    textlength.textColor = [UIColor colorWithWhite:0.333 alpha:1.000];
    [self.view addSubview:textlength];
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)sureIntroduceClick
{
    //保存名字
    [self postUserName:textfield.text];
}
- (void)postUserName:(NSString *)name
{

     AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSString *uid = [userDefaultes objectForKey:@"uid"];
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
    [dataDic setObject:name forKey:@"introduce"];
    if (uid!=nil) {
        [dataDic setObject:uid forKey:@"user"];
    }else{
    }
    NSString *str =[NSString stringWithFormat:@"http://123.57.1.143/api/user/%@/edit",uid];
    NSString *header = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    [manager.requestSerializer setValue:header forHTTPHeaderField:@"authorization"];
    [manager POST:str parameters:dataDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
        //读取字典类型NSDictionary类型的数据
        NSDictionary *myDictionary = [userDefaultes dictionaryForKey:@"myDictionary"];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:myDictionary];
        [dic setValue:name forKey:@"introduce"];
        myDictionary = dic;
        
        [userDefaultes setObject:myDictionary forKey:@"myDictionary"];
        //保存名字（注册成功后）
        [userDefaultes setObject:name forKey:@"introduce"];
        [userDefaultes synchronize];
        
        [self.navigationController popViewControllerAnimated:YES];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [JCAlertView showOneButtonWithTitle:@"网络异常" Message:@"确保在有Wifi或信号良好的地方重试" ButtonType:JCAlertViewButtonTypeDefault ButtonTitle:@"" Click:^{
            
        }];
        
    }];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    [textfield becomeFirstResponder];
}
//
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [textfield resignFirstResponder];
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (textView.text.length <= 40) {
        if ([text isEqualToString:@"\n"]) {
            [textfield resignFirstResponder];
            [self sureIntroduceClick];
        }
    } else {
        
    }
    return  YES;
}
- (void)textViewDidChange:(UITextView *)textView
{
    if (textfield.text.length<=0 ) {
        [sureBtn setEnabled:NO];
    }else if (textView.text.length > 40){
        [sureBtn setEnabled:NO];
//        textView.text = [textView.text substringToIndex:40];
        [textView deleteBackward];
    } else {
        textlength.text = [NSString stringWithFormat:@"%lu", 40 - textView.text.length];
        [sureBtn setEnabled:YES];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
